﻿using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
using WAU.DTOs.OrderModule;
using WAU.Library.RabbitMQ;
using WAU.Models.Framework;
using RabbitMQChannel = RabbitMQ.Client.IModel;

namespace WAU.Services.Routines
{
    /// <summary>
    /// 消息队列消费订单 Routine
    /// </summary>
    public class MQConsumeOrderRoutine : IRoutine
    {
        public const string ORDER_EXCHANGE_NAME = "order_exchange";
        public const string ORDER_QUEUE_NAME = "order_queue";

        /// <summary>
        /// Execute
        /// </summary>
        public void Execute()
        {
            Task.Run(() =>
            {
                IServiceScope serviceScope = GlobalReadOnlyVariables.ServiceProvider.CreateScope();
                RabbitMQChannel channel = serviceScope.ServiceProvider.GetRequiredService<ScopedRabbitMQModelLease>().Channel;

                channel.ExchangeDeclare(ORDER_EXCHANGE_NAME, "direct", true, false);
                channel.QueueDeclare(ORDER_QUEUE_NAME, true, false, false);
                channel.QueueBind(ORDER_QUEUE_NAME, ORDER_EXCHANGE_NAME, "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (sender, args) =>
                {
                    // 读取并反序列化 MQ 消息内容
                    string originMsg = Encoding.UTF8.GetString(args.Body.ToArray());
                    Console.WriteLine($"收到了订单消息 {originMsg}，当前时间为：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    OrderMQDTO orderMQDTO = JsonSerializer.Deserialize<OrderMQDTO>(originMsg);                    

                    // 创建订单
                    using (IServiceScope optServiceScope = GlobalReadOnlyVariables.ServiceProvider.CreateScope()) 
                    {
                        OrderService orderService = optServiceScope.ServiceProvider.GetRequiredService<OrderService>();
                        ExecResult execResult = orderService.CreateOrderFromMQ(orderMQDTO);
                        Console.WriteLine($"创建订单{(execResult.Success ? "成功" : "失败")}");
                    }                    
                };

                channel.BasicConsume(ORDER_QUEUE_NAME, true, consumer);
            });
        }
    }
}
